<?php

function escapeQuote($string){
	$string = str_replace("'","&#39;" ,$string);
	$string = str_replace('"', "&#34;" ,$string);
	return $string;
}

function htmlnumericentities($str){
  return preg_replace('/[^!-%\x27-;=?-~ ]/e', '"&#".ord("$0").chr(59)', $str);
}


function isAdminLoggedIn(){
	if(isUserLoggedIn()){
		return $_SESSION["useradmin"];
	}
	return false;
}

function isUserLoggedIn(){
	if(isset($_SESSION["userid"]) && $_SESSION["userid"] > 0){
		return true;
	}

	if(isset($_COOKIE["userid"]) && $_COOKIE["userid"] > 0){
		return loginUser(new User($_COOKIE["userid"]));
	}

	return false;
}

function loginUser($user, $remember = false){
	if (isset($user->attributes->id)){
			$_SESSION['userid'] = $user->attributes->id;
			$_SESSION['userlang'] = $user->attributes->lang;
			$_SESSION['useradmin'] = $user->attributes->admin;
			$_SESSION['userfirstname'] = $user->attributes->firstName;
			$_SESSION['userlastname'] = $user->attributes->lastName;
			$_SESSION['userprevlastlogin'] = $user->attributes->lastLogin;
			$user->attributes->lastLogin = time();
			$user->save(false,false,false);
			if($remember){
				setcookie("userid", $user->attributes->id,time() + (86400 * 7), '/');
			}
			return true;
		}

	$_SESSION['user'] = "";
	return false;
}

function logout(){
	session_unset();
	setcookie("userid","",time() - 3600, "/");
}

function getUserLoggedIn(){
	if(isUserLoggedIn()){
			return new User($_SESSION["userid"]);
	}

	return null;
}

function getUserLoggedInId(){
	if(isUserLoggedIn()){
		return $_SESSION['userid'];
	}

	return null;
}

function curPageURL() {
 	$pageURL = 'http';
 	if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 		$pageURL .= "://";
 	if (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != "80") {
  		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 	} else {
  		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 	}
 	return $pageURL;
}

function curPageBasic() {

	$page = curPageURL();
	$questionSign = strpos($page, '?');
	if($questionSign > 0)
		$newPage = substr($page, 0,$questionSign);
	else
		$newPage = $page;

	return $newPage;
}


function contains($string, $search){
	$pos = strpos($string,$search);

	if($pos === false) {
	 	return false;
	}
	else {
	 	return true;
	}
}

function forward($location = "") {
	if (!headers_sent()) {
		if ($location) {
			header("Location: {$location}");
			exit;
		} else if ($location === '') {
			exit;
		}
	}

	return false;
}

function getInput($key, $default = ''){
	return getInputArray($key, $_REQUEST, $default);
}

function getInputArray($key, $array, $default = ''){
	$return = $default;
	if(array_key_exists($key,$array) && $array[$key] !== ''){
		$return = $array[$key];
	}
	return $return;
}


function getIcon($class, $id, $size = "normal"){
	$file = UPLOADPATH . $class . "/" . $id . "/icon" . $size .".jpg";

	if (file_exists($file)){
		return UPLOADWWW . $class . "/" . $id . "/icon" . $size .".jpg";
	}else{
		return WWWROOT .  "images/" . $class . "/icon" . $size .".jpg";
	}
}

function generatePassword($length=6,$level=2){

   list($usec, $sec) = explode(' ', microtime());
   srand((float) $sec + ((float) $usec * 100000));

   $validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
   $validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";

   $password  = "";
   $counter   = 0;

   while ($counter < $length) {
     $actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

     // All character must be different
     if (!strstr($password, $actChar)) {
        $password .= $actChar;
        $counter++;
     }
   }

   return $password;
}

function validateImageFile($image){
	$imagesTypes = explode(",", IMAGEEXTENSIONS);
	$imageData = getimagesize($image);
	foreach($imagesTypes as $type){
		if($type == $imageData["mime"]){
			return true;
		}
	}
	return false;
}

function validateVideoFile($video){
	$videoTypes = explode(",", VIDEOEXTENSIONS);
	foreach($videoTypes as $type){
		if($type == $video["type"]){
			return true;
		}
	}
	return false;
}

function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }

 function is_email($email){
	$res = ereg('^[a-z]+([\.]?[a-z0-9_-]+)*@'.// usuario
				'[a-z0-9]+([\.-]+[a-z0-9]+)*\.[a-z]{2,}$', // server.
				$email);
	return $res;
}


function validateUrl($url){
	return ereg('^(.*)\/$/$1', $url);
}

 function getArrayFromAttributesFormultipleValuesWithSelect($attributes, $valueName, $comboName){
 	$array = array();
 	$counter = 0;
 	foreach($attributes as $att){
 		$array[$counter] = new stdClass();
 		$array[$counter]->value = $att->attributes->$valueName;
 		$array[$counter]->comboValue = $att->attributes->$comboName;
 		$array[$counter]->id = $att->attributes->id;
 		//$array[$counter]->lastValueType = $att->attributes->lastValueType;
 		$counter++;
 	}
 	return $array;

 }

 function getArrayFromAttributes($attributes, $name){
 	$array = array();
 	$counter = 0;
 	foreach($attributes as $att){
 		$array[$counter] = new stdClass();
 		$array[$counter]->value = $att->attributes->$name;
 		$array[$counter]->id = $att->attributes->id;
 		$counter++;
 	}
 	return $array;

 }

 function getArrayForSelect($attributes, $name){
 	$array = array();
 	foreach($attributes as $att){
 		$array[$att->attributes->id] = $att->attributes->$name;
 	}
 	return $array;

 }

 function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
	if ($unit == "M"){
	 	return ($miles * 1.609344*1000);
	}
	else{
	     return $miles;
	    }
  }
}

 function getProvince($key){
 	$provinces = getProvinces();
 	return langEcho($provinces[$key]);
 }

 function getProvinces($country = "Argentina") {

 		switch($country){

 			case "Argentina":
 				$provinces = array(

 					"BuenosAires" => "provinces:BuenosAires",
 					"CiudadAutonomaDeBuenosAires" => "provinces:CiudadAutonomaDeBuenosAires",
 					"Catamarca" => "provinces:Catamarca",
 					"Chaco" => "provinces:Chaco",
 					"Chubut" => "provinces:Chubut",
 					"Corrientes" => "provinces:Corrientes",
					"Cordoba" => "provinces:Cordoba",
  					"EntreRios" => "provinces:EntreRios",
  					"Formosa" => "provinces:Formosa",
  					"Jujuy" => "provinces:Jujuy",
  					"LaPampa" => "provinces:LaPampa",
 					"LaRioja" => "provinces:LaRioja",
					"Mendoza" => "provinces:Mendoza",
 					"Misiones" => "provinces:Misiones",
 					"Neuquen" => "provinces:Neuquen",
 					"RioNegro" => "provinces:RioNegro",
 					"Salta" => "provinces:Salta",
 					"SanJuan" => "provinces:SanJuan",
 					"SanLuis" => "provinces:SanLuis",
 					"SantaCruz" => "provinces:SantaCruz",
					"SantaFe" => "provinces:SantaFe",
 					"SantiagoDelEstero" => "provinces:SantiagoDelEstero",
 					"TierraDelFuego" => "provinces:TierraDelFuego",
 					"Tucuman" => "provinces:Tucuman",
 				);

 				return $provinces;

 			default:
 				return array();
 		}

}

function getCountries () {
		$countries = array(
		"Afghanistan" => "countries:Afghanistan",
		"AfricanUnion" => "countries:AfricanUnion",
		"Albania" => "countries:Albania",
		"Algeria" => "countries:Algeria",
		"AmericanSamoa" => "countries:AmericanSamoa",
		"Andorra" => "countries:Andorra",
		"Angola" => "countries:Angola",
		"Anguilla" => "countries:Anguilla",
		"Antarctica" => "countries:Antarctica",
		"AntiguaAndBarbuda" => "countries:AntiguaAndBarbuda",
		"ArabLeague" => "countries:ArabLeague",
		"Argentina" => "countries:Argentina",
		"Armenia" => "countries:Armenia",
		"Aruba" => "countries:Aruba",
		"Australia" => "countries:Australia",
		"Austria" => "countries:Austria",
		"Azerbaijan" => "countries:Azerbaijan",
		"Bahamas" => "countries:Bahamas",
		"Bahrain" => "countries:Bahrain",
		"Bangladesh" => "countries:Bangladesh",
		"Barbados" => "countries:Barbados",
		"Belarus" => "countries:Belarus",
		"Belgium" => "countries:Belgium",
		"Belize" => "countries:Belize",
		"Benin" => "countries:Benin",
		"Bermuda" => "countries:Bermuda",
		"Bhutan" => "countries:Bhutan",
		"Bolivia" => "countries:Bolivia",
		"BosniaAndHerzegovina" => "countries:BosniaAndHerzegovina",
		"Botswana" => "countries:Botswana",
		"Brazil" => "countries:Brazil",
		"Brunei" => "countries:Brunei",
		"Bulgaria" => "countries:Bulgaria",
		"BurkinaFaso" => "countries:BurkinaFaso",
		"Burundi" => "countries:Burundi",
		"Cambodja" => "countries:Cambodja",
		"Cameroon" => "countries:Cameroon",
		"Canada" => "countries:Canada",
		"CapeVerde" => "countries:CapeVerde",
		"CaymanIslands" => "countries:CaymanIslands",
		"CentralAfricanRepublic" => "countries:CentralAfricanRepublic",
		"Chad" => "countries:Chad",
		"Chile" => "countries:Chile",
		"China" => "countries:China",
		"Colombia" => "countries:Colombia",
		"Commonwealth" => "countries:Commonwealth",
		"Comoros" => "countries:Comoros",
		"Congo-Brazzaville" => "countries:Congo-Brazzaville",
		"Congo-Kinshasa(Zaire)" => "countries:Congo-Kinshasa(Zaire)",
		"CookIslands" => "countries:CookIslands",
		"CostaRica" => "countries:CostaRica",
		"CotedIvoire" => "countries:CotedIvoire",
		"Croatia" => "countries:Croatia",
		"Cuba" => "countries:Cuba",
		"Cyprus" => "countries:Cyprus",
		"CzechRepublic" => "countries:CzechRepublic",
		"Denmark" => "countries:Denmark",
		"Djibouti" => "countries:Djibouti",
		"DominicanRepublic" => "countries:DominicanRepublic",
		"Dominica" => "countries:Dominica",
		"Ecuador" => "countries:Ecuador",
		"Egypt" => "countries:Egypt",
		"ElSalvador" => "countries:ElSalvador",
		"England" => "countries:England",
		"EquatorialGuinea" => "countries:EquatorialGuinea",
		"Eritrea" => "countries:Eritrea",
		"Estonia" => "countries:Estonia",
		"Ethiopia" => "countries:Ethiopia",
		"EuropeanUnion" => "countries:EuropeanUnion",
		"Faroes" => "countries:Faroes",
		"Fiji" => "countries:Fiji",
		"Finland" => "countries:Finland",
		"France" => "countries:France",
		"Gabon" => "countries:Gabon",
		"Gambia" => "countries:Gambia",
		"Georgia" => "countries:Georgia",
		"Germany" => "countries:Germany",
		"Ghana" => "countries:Ghana",
		"Gibraltar" => "countries:Gibraltar",
		"Greece" => "countries:Greece",
		"Greenland" => "countries:Greenland",
		"Grenada" => "countries:Grenada",
		"Guadeloupe" => "countries:Guadeloupe",
		"Guademala" => "countries:Guademala",
		"Guam" => "countries:Guam",
		"Guernsey" => "countries:Guernsey",
		"Guinea-Bissau" => "countries:Guinea-Bissau",
		"Guinea" => "countries:Guinea",
		"Guyana" => "countries:Guyana",
		"Haiti" => "countries:Haiti",
		"Honduras" => "countries:Honduras",
		"HongKong" => "countries:HongKong",
		"Hungary" => "countries:Hungary",
		"Iceland" => "countries:Iceland",
		"India" => "countries:India",
		"Indonesia" => "countries:Indonesia",
		"Iran" => "countries:Iran",
		"Iraq" => "countries:Iraq",
		"Ireland" => "countries:Ireland",
		"IslamicConference" => "countries:IslamicConference",
		"IsleofMan" => "countries:IsleofMan",
		"Israel" => "countries:Israel",
		"Italy" => "countries:Italy",
		"Jamaica" => "countries:Jamaica",
		"Japan" => "countries:Japan",
		"Jersey" => "countries:Jersey",
		"Jordan" => "countries:Jordan",
		"Kazakhstan" => "countries:Kazakhstan",
		"Kenya" => "countries:Kenya",
		"Kiribati" => "countries:Kiribati",
		"Kosovo" => "countries:Kosovo",
		"Kuwait" => "countries:Kuwait",
		"Kyrgyzstan" => "countries:Kyrgyzstan",
		"Laos" => "countries:Laos",
		"Latvia" => "countries:Latvia",
		"Lebanon" => "countries:Lebanon",
		"Lesotho" => "countries:Lesotho",
		"Liberia" => "countries:Liberia",
		"Libya" => "countries:Libya",
		"Liechtenstein" => "countries:Liechtenstein",
		"Lithuania" => "countries:Lithuania",
		"Luxembourg" => "countries:Luxembourg",
		"Macao" => "countries:Macao",
		"Macedonia" => "countries:Macedonia",
		"Madagascar" => "countries:Madagascar",
		"Malawi" => "countries:Malawi",
		"Malaysia" => "countries:Malaysia",
		"Maldives" => "countries:Maldives",
		"Mali" => "countries:Mali",
		"Malta" => "countries:Malta",
		"MarshallIslands" => "countries:MarshallIslands",
		"Martinique" => "countries:Martinique",
		"Mauritania" => "countries:Mauritania",
		"Mauritius" => "countries:Mauritius",
		"Mexico" => "countries:Mexico",
		"Micronesia" => "countries:Micronesia",
		"Moldova" => "countries:Moldova",
		"Monaco" => "countries:Monaco",
		"Mongolia" => "countries:Mongolia",
		"Montenegro" => "countries:Montenegro",
		"Montserrat" => "countries:Montserrat",
		"Morocco" => "countries:Morocco",
		"Mozambique" => "countries:Mozambique",
		"Myanmar(Burma)" => "countries:Myanmar(Burma)",
		"Namibia" => "countries:Namibia",
		"Nauru" => "countries:Nauru",
		"Nepal" => "countries:Nepal",
		"NetherlandsAntilles" => "countries:NetherlandsAntilles",
		"Netherlands" => "countries:Netherlands",
		"NewCaledonia" => "countries:NewCaledonia",
		"NewZealand" => "countries:NewZealand",
		"Nicaragua" => "countries:Nicaragua",
		"Nigeria" => "countries:Nigeria",
		"Niger" => "countries:Niger",
		"NorthernCyprus" => "countries:NorthernCyprus",
		"NorthernIreland" => "countries:NorthernIreland",
		"NorthKorea" => "countries:NorthKorea",
		"Norway" => "countries:Norway",
		"OlimpicMovement" => "countries:OlimpicMovement",
		"Oman" => "countries:Oman",
		"Pakistan" => "countries:Pakistan",
		"Palau" => "countries:Palau",
		"Palestine" => "countries:Palestine",
		"Panama" => "countries:Panama",
		"PapuaNewGuinea" => "countries:PapuaNewGuinea",
		"Paraguay" => "countries:Paraguay",
		"Peru" => "countries:Peru",
		"Philippines" => "countries:Philippines",
		"Poland" => "countries:Poland",
		"Portugal" => "countries:Portugal",
		"PuertoRico" => "countries:PuertoRico",
		"Qatar" => "countries:Qatar",
		"Reunion" => "countries:Reunion",
		"Romania" => "countries:Romania",
		"RussianFederation" => "countries:RussianFederation",
		"Rwanda" => "countries:Rwanda",
		"SaintLucia" => "countries:SaintLucia",
		"Samoa" => "countries:Samoa",
		"SanMarino" => "countries:SanMarino",
		"SaoTomeAndPrincipe" => "countries:SaoTomeAndPrincipe",
		"SaudiArabia" => "countries:SaudiArabia",
		"Scotland" => "countries:Scotland",
		"Senegal" => "countries:Senegal",
		"Serbia" => "countries:Serbia",
		"Seyshelles" => "countries:Seyshelles",
		"SierraLeone" => "countries:SierraLeone",
		"Singapore" => "countries:Singapore",
		"Slovakia" => "countries:Slovakia",
		"Slovenia" => "countries:Slovenia",
		"SolomonIslands" => "countries:SolomonIslands",
		"Somalia" => "countries:Somalia",
		"Somaliland" => "countries:Somaliland",
		"SouthAfrica" => "countries:SouthAfrica",
		"SouthKorea" => "countries:SouthKorea",
		"Spain" => "countries:Spain",
		"SriLanka" => "countries:SriLanka",
		"StKittsAndNevis" => "countries:StKittsAndNevis",
		"StVincentAndtheGrenadines" => "countries:StVincentAndtheGrenadines",
		"Sudan" => "countries:Sudan",
		"Suriname" => "countries:Suriname",
		"Swaziland" => "countries:Swaziland",
		"Sweden" => "countries:Sweden",
		"Switzerland" => "countries:Switzerland",
		"Syria" => "countries:Syria",
		"Tahiti(FrenchPolinesia)" => "countries:Tahiti(FrenchPolinesia)",
		"Taiwan" => "countries:Taiwan",
		"Tajikistan" => "countries:Tajikistan",
		"Tanzania" => "countries:Tanzania",
		"Thailand" => "countries:Thailand",
		"Timor-Leste" => "countries:Timor-Leste",
		"Togo" => "countries:Togo",
		"Tonga" => "countries:Tonga",
		"TrinidadAndTobago" => "countries:TrinidadAndTobago",
		"Tunisia" => "countries:Tunisia",
		"Turkey" => "countries:Turkey",
		"Turkmenistan" => "countries:Turkmenistan",
		"TurksandCaicosIslands" => "countries:TurksandCaicosIslands",
		"Tuvalu" => "countries:Tuvalu",
		"Uganda" => "countries:Uganda",
		"Ukraine" => "countries:Ukraine",
		"UnitedArabEmirates" => "countries:UnitedArabEmirates",
		"UnitedKingdom(GreatBritain)" => "countries:UnitedKingdom(GreatBritain)",
		"UnitedNations" => "countries:UnitedNations",
		"UnitedStatesofAmerica" => "countries:UnitedStatesofAmerica",
		"Uruguay" => "countries:Uruguay",
		"Uzbekistan" => "countries:Uzbekistan",
		"Vanutau" => "countries:Vanutau",
		"VaticanCity" => "countries:VaticanCity",
		"Venezuela" => "countries:Venezuela",
		"VietNam" => "countries:VietNam",
		"VirginIslandsBritish" => "countries:VirginIslandsBritish",
		"VirginIslandsUS" => "countries:VirginIslandsUS",
		"Wales" => "countries:Wales",
		"WesternSahara" => "countries:WesternSahara",
		"Yemen" => "countries:Yemen",
		"Zambia" => "countries:Zambia",
		"Zimbabwe" => "countries:Zimbabwe"
		);
		return $countries;
}

?>